package com.akhuting.shearphoto.controller;

import com.akhuting.shearphoto.kit.ImageKit;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.upload.UploadFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * IndexController on shearphoto
 *
 * @author <a href="mailto:akhuting@hotmail.com">Alex Yang</a>
 * @date 2015年08月18日 17:49
 */
public class IndexController extends Controller {

    public void index() {
        render("index.html");
    }

    /**
     * 接收图片裁剪
     * @throws IOException
     */
    public void shearphoto() throws IOException {

        String JSdate = getPara("JSdate");
        JSONObject jsonObject = JSON.parseObject(JSdate);
        if (jsonObject == null
                || !jsonObject.containsKey("url")
                || !jsonObject.containsKey("R")
                || !jsonObject.containsKey("X")
                || !jsonObject.containsKey("Y")
                || !jsonObject.containsKey("IW")
                || !jsonObject.containsKey("IH")
                || !jsonObject.containsKey("P")
                || !jsonObject.containsKey("FW")
                || !jsonObject.containsKey("FH")) {
            setAttr("erro", "服务端接收到的数据缺少参数");
            renderJson();
            return;
        }

        File file = new File(PathKit.getWebRootPath() + File.separator + jsonObject.getString("url"));
        if (!file.exists()) {
            setAttr("erro", "此图片路径有误");
            renderJson();
            return;
        }

        String type = ImageKit.getImageFormat(file);
        String srcPath = PathKit.getWebRootPath() + File.separator + PropKit.get("temp") + File.separator + System.currentTimeMillis() + "." + type;
        BufferedImage bufferedImage = ImageIO.read(file);

        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();

        int rotate = jsonObject.getIntValue("R");

        if (rotate == -90 || rotate == -270) {
            width = bufferedImage.getHeight();
            height = bufferedImage.getWidth();
        }

        bufferedImage = rotateImage(rotate, bufferedImage);

        ImageKit.abscut(bufferedImage, srcPath, type, jsonObject.getIntValue("X"), jsonObject.getIntValue("Y"), jsonObject.getIntValue("IW"), jsonObject.getIntValue("IH"), width, height);

        JSONArray array = zipImage(srcPath, type);

        ImageKit.delFile(srcPath);

        renderJson(array);
    }

    /**
     * 压缩图片
     *
     * @param srcPath
     * @param type
     * @return
     */
    private JSONArray zipImage(String srcPath, String type) {
        String widthConfig = PropKit.get("width");

        JSONArray objects = JSONArray.parseArray(widthConfig);
        JSONArray array = new JSONArray();
        for (Object object : objects) {
            JSONObject result = new JSONObject();
            JSONObject o = (JSONObject) object;
            int toWidth = o.getIntValue("width");
            String proportionalStr = PropKit.get("proportional");
            int index = proportionalStr.indexOf("/");
            double proportional = Double.
                    parseDouble(proportionalStr.substring(0, index))
                    / Double.parseDouble(proportionalStr.substring(index + 1));

            int toHeigth = (int) (toWidth / proportional);
            String zoomImage = ImageKit.zoomImage(new File(srcPath), type, toWidth, toHeigth);
            result.put("ImgHeight", toHeigth);
            result.put("ImgWidth", toWidth);
            result.put("ImgName", "img_" + toWidth);
            result.put("ImgUrl", zoomImage);
            array.add(result);
        }
        return array;
    }

    /**
     * 旋转图片
     * @param rotate
     * @param image
     * @return
     */
    private BufferedImage rotateImage(int rotate, BufferedImage image) {
        if (rotate == -90 || rotate == -180 || rotate == -270) {
            image = ImageKit.rotateImage(image, Math.abs(rotate));
        }
        return image;
    }

    /**
     * 接收图片上传
     */
    public void upload() {
        UploadFile upFile = getFile("UpFile");

        JSONObject result = new JSONObject();
        if (!ImageKit.isImageFile(upFile.getFile())) {
            result.put("erro", "文件格式错误");
        } else {
            result.put("success", PropKit.get("upload") + "/" + upFile.getOriginalFileName());
        }
        renderHtml(result.toString());
    }
}
